import { createContext, Component, ComponentType, useContext, useState, Dispatch, SetStateAction } from "react";
export type SetupContext<T> = Dispatch<SetStateAction<T>>

function createInjection<T>({ defaultState, Injection } : { defaultState: T, Injection: ComponentType<{setupContext: SetupContext<T>}> }) {
    const LoginContext = createContext<T>(defaultState);

    const InjectWrapper = ({ children }: {
        children: JSX.Element
    }) => {
        const [context, setContext] = useState(defaultState);

        return (
            <LoginContext.Provider value={context}>
                <Injection setupContext={setContext} />
                {children}
            </LoginContext.Provider>
        )
    }

    class NewApp extends Component {
        render() {
            return <></>
        }
    }

    const inject = (App: ComponentType) => {
        NewApp.prototype.render = function render(this: NewApp) {
            return (
                <InjectWrapper>
                    <App {...this.props} />
                </InjectWrapper>
            )
        }

        return NewApp
    }

    function useInject() {
        return useContext(LoginContext);
    }

    const values: [(App: ComponentType) => typeof NewApp, () => T] = [inject, useInject];

    return values
}

export default createInjection